package com.kandinfo.survey.question.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.service.AbstractService;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.survey.common.constants.StatusConstant;
import com.kandinfo.survey.common.domain.QuestionRelation;
import com.kandinfo.survey.common.repository.QuestionRelationRepository;
import com.kandinfo.survey.question.dto.QuesRelationRequestDto;
import com.kandinfo.survey.question.service.QuestionRelationService;

@Service
public class QuestionRelationServiceImpl extends AbstractService<QuestionRelation, Long, QuestionRelationRepository> implements QuestionRelationService {
    
    private static final Logger logger = LoggerFactory.getLogger(QuestionRelationServiceImpl.class);
    
    @Resource
    public void setQuestionRelationRepository(QuestionRelationRepository questionRelationRepository) {
        super.setRepository(questionRelationRepository);
    }
    
    @Override
    @Transactional
    public ResultDto connectQues(List<QuesRelationRequestDto> requestDtoList) {
        if (CollectionUtils.isEmpty(requestDtoList)) {
            return ResultDtoFactory.toNack("无要关联的数据!");
        }
        
        User currentUser = SecurityContext.getInstance().getCurrentUser();
        List<QuestionRelation> saveList = new ArrayList<QuestionRelation>();
        try {
            requestDtoList.forEach(quesRelationRequestDto -> {
                QuestionRelation domain = new QuestionRelation();
                domain.setQidA(quesRelationRequestDto.getQidA());
                domain.setQidB(quesRelationRequestDto.getQidB());
                domain.setStatus(StatusConstant.NORMALLY_USE);
                domain.setType(0 + "");
                domain.setCreateTs(new Date());
                domain.setCreateBy(currentUser == null ? 1L : currentUser.getId());
                
                saveList.add(domain);
            });
        } catch (Exception e) {
            logger.error("quesRelationRequestDto -> QuestionRelation 转换错误! ", e.toString());
            return ResultDtoFactory.toNack("关联失败!");
        }
        
        if (!saveList.isEmpty()) {
            repository.save(saveList);
        }
        return ResultDtoFactory.toAck("关联成功!");
    }

}
